<!--
# coding=UTF-8
# Copyright (c) 2025 Bird Software Solutions Ltd
# This program and the accompanying materials
# are made available under the terms of the Eclipse Public License 2.0
# which accompanies this distribution, and is available at
# https://www.eclipse.org/legal/epl-2.0/
#
# SPDX-License-Identifier: EPL-2.0
#
# Contributors:
#    Neil Mackenzie - initial API and implementation
#    Benjamin Arfa - improvements
#
-->
{% extends "pybirdai/workflow/base.html" %} {% block breadcrumb_items %}
<span class="breadcrumb-separator">›</span>
<a href="{% url 'pybirdai:workflow_task' task_number=2 operation='do' %}"
    >Task 2: SMCubes Transformation Rules</a
>
<span class="breadcrumb-separator">›</span>
<span>Do</span>
{% endblock %} {% block workflow_content %}
<div class="task-content">
    <h1>Task 2: SMCubes Transformation Rules Creation - Do</h1>

    {% if task_execution.status != 'pending' %}
    <div class="alert alert-success">
        <strong>At least 1 Subtask Completed</strong>
        <p>SMCubes transformation rules have been created successfully.</p>
        <a
            href="{% url 'pybirdai:workflow_task' task_number=2 operation='review' %}"
            class="operation-btn btn-primary"
            >Go to Review</a
        >
    </div>
    {% elif task_execution.status == 'failed' %}
    <div class="alert alert-danger">
        <strong>✗ Task Failed</strong>
        <p>{{ task_execution.error_message }}</p>
        <p>Please fix the issues and try again.</p>
    </div>
    {% elif task_execution.status == 'running' %}
    <div class="alert alert-info">
        <strong>🔄 Task Running</strong>
        <p>Transformation rules creation is in progress...</p>
        <div class="progress">
            <div
                class="progress-bar progress-bar-striped progress-bar-animated"
                style="width: {{ task_execution.execution_data.progress|default:0 }}%"
            ></div>
        </div>
    </div>
    {% endif %}

    <h2>Transformation Rules Creation Process</h2>

    <div class="subtask-list">
        <h3>Subtasks to be executed:</h3>

        <div class="subtask-item">
            <h4>1. Filter Creation</h4>
            <p>Generate SMCubes filters from business rules</p>
            <ul>
                <li>Parse filter definitions</li>
                <li>Create filter metadata</li>
                <li>Validate filter logic</li>
            </ul>
            {% if task_execution.execution_data.filters_created %}
            <span class="status-badge completed">✓ Completed</span>
            {% else %}
            <span class="status-badge pending">⏳ Pending</span>
            {% endif %}
            <a
                href="{% url 'pybirdai:workflow_task_substep_with_loading' task_number=2 substep_name='generate_all_filters' %}"
                class="operation-btn btn-sm btn-primary"
            >
                Run Generate Filters
            </a>
        </div>

        <div class="subtask-item">
            <h4>2. Join Rules Creation</h4>
            <p>Generate join metadata for data relationships</p>
            <ul>
                <li>Analyze data relationships</li>
                <li>Create join specifications</li>
                <li>Generate executable joins</li>
            </ul>
            {% if task_execution.execution_data.joins_metadata_created %}
            <span class="status-badge completed">✓ Completed</span>
            {% else %}
            <span class="status-badge pending">⏳ Pending</span>
            {% endif %}
            <a
                href="{% url 'pybirdai:workflow_task_substep_with_loading' task_number=2 substep_name='create_joins_metadata' %}"
                class="operation-btn btn-sm btn-primary"
            >
                Run Create Joins Metadata
            </a>
        </div>
    </div>

    <!-- {% if task_execution.status == 'pending' %}
    <div id="task2-status" style="display: none"></div>
    <form id="task2-form" method="post" style="margin-top: 30px">
        {% csrf_token %}

        <div class="execution-options">
            <h3>Execution Options</h3>

            <div class="form-check">
                <input
                    class="form-check-input"
                    type="checkbox"
                    name="generate_all_filters"
                    id="generate_all_filters"
                    checked
                />
                <label class="form-check-label" for="generate_all_filters">
                    Generate All Available Filters
                </label>
            </div>

            <div class="form-check">
                <input
                    class="form-check-input"
                    type="checkbox"
                    name="create_joins_metadata"
                    id="create_joins_metadata"
                    checked
                />
                <label class="form-check-label" for="create_joins_metadata">
                    Create Join Metadata
                </label>
            </div>

            <div class="form-check">
                <input
                    class="form-check-input"
                    type="checkbox"
                    name="validate_filters"
                    id="validate_filters"
                    checked
                />
                <label class="form-check-label" for="validate_filters">
                    Validate Filter Logic
                </label>
            </div>

            <div class="form-check">
                <input
                    class="form-check-input"
                    type="checkbox"
                    name="optimize_joins"
                    id="optimize_joins"
                    checked
                />
                <label class="form-check-label" for="optimize_joins">
                    Optimize Join Execution Order
                </label>
            </div>
        </div>

        <button type="submit" class="btn btn-primary">
            Start Transformation Rules Creation
        </button>
        <a
            href="{% url 'pybirdai:workflow_dashboard' %}"
            class="btn btn-secondary"
            >Cancel</a
        >
    </form>
    {% endif %} -->
</div>

<style>
    .subtask-list {
        margin: 20px 0;
    }

    .subtask-item {
        background: #f8f9fa;
        border: 1px solid #dee2e6;
        border-radius: 8px;
        padding: 20px;
        margin-bottom: 15px;
    }

    .subtask-item h4 {
        margin-top: 0;
        margin-bottom: 10px;
        color: #495057;
    }

    .subtask-item ul {
        margin: 10px 0;
        padding-left: 20px;
    }

    .status-badge {
        display: inline-block;
        padding: 4px 12px;
        border-radius: 4px;
        font-size: 12px;
        font-weight: bold;
        margin-top: 10px;
    }

    .status-badge.pending {
        background-color: #e9ecef;
        color: #6c757d;
    }

    .status-badge.running {
        background-color: #cfe2ff;
        color: #084298;
    }

    .status-badge.completed {
        background-color: #d1e7dd;
        color: #0f5132;
    }

    .execution-options {
        background: #f8f9fa;
        padding: 20px;
        border-radius: 8px;
        margin-bottom: 20px;
    }

    .execution-options h3 {
        margin-top: 0;
        margin-bottom: 15px;
    }

    .form-check {
        margin-bottom: 10px;
    }

    .progress {
        height: 20px;
        margin-top: 10px;
    }

    .progress-bar {
        background-color: #0d6efd;
    }
</style>

<script>
    // Auto-refresh if task is running

    // Handle form submission with AJAX
    document.addEventListener('DOMContentLoaded', function() {
        const form = document.getElementById('task2-form');
        const statusDiv = document.getElementById('task2-status');

        if (form) {
            form.addEventListener('submit', function(e) {
                e.preventDefault();

                // Show processing message
                statusDiv.innerHTML = '<div class="alert alert-info"><strong>🔄 Processing...</strong> Starting SMCubes rules creation. This may take a few minutes...</div>';
                statusDiv.style.display = 'block';

                // Disable submit button
                const submitBtn = form.querySelector('button[type="submit"]');
                submitBtn.disabled = true;
                submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Creating...';

                // Submit form via AJAX
                fetch(form.action || window.location.href, {
                    method: 'POST',
                    body: new FormData(form),
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest',
                        'X-CSRFToken': form.querySelector('[name=csrfmiddlewaretoken]').value
                    }
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        statusDiv.innerHTML = '<div class="alert alert-success"><strong>✓ Success!</strong> ' + (data.message || 'SMCubes rules creation completed successfully.') + '</div>';
                        // Refresh page after 2 seconds to show completed status
                        setTimeout(function() {
                            location.reload();
                        }, 2000);
                    } else {
                        statusDiv.innerHTML = '<div class="alert alert-danger"><strong>✗ Error!</strong> ' + (data.message || 'SMCubes rules creation failed.') + '</div>';
                        submitBtn.disabled = false;
                        submitBtn.innerHTML = 'Start SMCubes Rules Creation';
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    statusDiv.innerHTML = '<div class="alert alert-danger"><strong>✗ Error!</strong> An unexpected error occurred. Please try again.</div>';
                    submitBtn.disabled = false;
                    submitBtn.innerHTML = 'Start SMCubes Rules Creation';
                });
            });
        }

    });
</script>
{% endblock %}
